package com.robotserver.orders.service.impl;

import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowQueryResult;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.param.JdOrderSyncParam;
import com.robotserver.orders.service.JdCpsOrderService;
import com.robotserver.orders.service.JdOrderManualService;
import com.robotserver.orders.service.JdOrderSyncService;
import com.robotserver.orders.vo.JdOrderTimeVO;
import com.robotserver.orders.vo.jdcpsorder.JdCpsOrderResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/12/18 15:25
 * @Description:
 */
@Service
public class JdOrderManualServiceImpl implements JdOrderManualService {

    private static Logger logger = LoggerFactory.getLogger(JdOrderManualServiceImpl.class);

    private static int pagesize = 100;

    private static int type = 3;            // 按照更新时间来查询

    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private JdCpsOrderService jdCpsOrderService;

    @Autowired
    private JdOrderSyncService jdOrderSyncService;
    @Value("${jd.sdk.url}")
    private String jdSdkUrl;

    @Async("taskExecutor")
    @Override
    public void remotePull(JdOrderSyncParam jdOrderSyncParam) {
        String jd_appkey = sysSettingMapper.getByKey("jd_appkey");
        String jd_appsecret = sysSettingMapper.getByKey("jd_appsecret");

        //二个都要拉取
        String[] jdAppKeyArr = jd_appkey.split(",");
        String[] jdAppsecretArr = jd_appsecret.split(",");

        if(jdAppKeyArr != null && jdAppsecretArr != null && jdAppKeyArr.length == jdAppsecretArr.length) {
            for (int i = 0; i < jdAppKeyArr.length; i++) {
                try {
                    JdClient client=new DefaultJdClient(jdSdkUrl,"", jdAppKeyArr[i], jdAppsecretArr[i]);
                    //List<String> jdOrderTimeScope = DateUtil.getJdOrderTimeScope(jdOrderSyncParam.getBegin_time(),jdOrderSyncParam.getEnd_time());
                    List<JdOrderTimeVO> jdOrderTimeScope = DateUtil.getJdOrderTimeScope_ByAppKey(jdOrderSyncParam.getBegin_time(),jdOrderSyncParam.getEnd_time());
                    for (JdOrderTimeVO jdOrderTimeVO:jdOrderTimeScope){
                        syncTimeUnitOrder(jdOrderTimeVO,jdOrderSyncParam.getAuthKey(),jdOrderSyncParam.getDownTimeType(),1,client,jdOrderSyncParam.getType());
                    }
                }catch (Exception e){
                    logger.error("---京东联盟下载失败，jdAppKey={},jdAppsecret={}", jdAppKeyArr[i], jdAppsecretArr[i]);
                }

            }
        }
    }

    @Override
    public void syncTimeUnitOrder(JdOrderTimeVO jdOrderTimeVO, String authKey,int downTimeType, int pageNo, JdClient client,Integer type) {
        try {
            if (type==null || type==1){
                UnionOpenOrderRowQueryRequest request=new UnionOpenOrderRowQueryRequest();
                OrderRowReq orderReq=new OrderRowReq();
                orderReq.setPageIndex(pageNo);
                orderReq.setPageSize(pagesize);
                orderReq.setType(downTimeType);
                orderReq.setStartTime(jdOrderTimeVO.getBeginTime());
                orderReq.setEndTime(jdOrderTimeVO.getEndTime());
                orderReq.setKey(authKey);
                orderReq.setType(type);
                orderReq.setFields("goodsInfo,categoryInfo"); //筛选出参，多项逗号分隔，目前支持：categoryInfo、goodsInfo
                request.setOrderReq(orderReq);
                UnionOpenOrderRowQueryResponse response = client.execute(request);
                if (response!=null){
                    OrderRowQueryResult queryResult = response.getQueryResult();
                    if(queryResult != null){
                        // 处理订单入库
                        jdOrderSyncService.ordersAdd(queryResult.getData());
                        if (queryResult.getHasMore()!=null && queryResult.getHasMore()){
                            pageNo = pageNo+1;
                            syncTimeUnitOrder(jdOrderTimeVO,authKey,downTimeType,pageNo,client,type);
                        }
                    }
                }
            }else{
//                // 京佣计划
                JdCpsOrderResp jdCpsOrderResp = jdCpsOrderService.getCpsOrders(authKey,jdOrderTimeVO,pageNo,downTimeType);
                if (jdCpsOrderResp!=null){
                    if (jdCpsOrderResp.getData()!=null &&
                            jdCpsOrderResp.getData().getResult()!=null && jdCpsOrderResp.getData().getResult().size()>0){
                        // 处理订单入库
                        jdCpsOrderService.orderAdd_byAppKey(jdCpsOrderResp.getData());
                        pageNo = pageNo+1;
                        syncTimeUnitOrder(jdOrderTimeVO,authKey,downTimeType,pageNo,client,type);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("jd sync order err:",e);
        }
    }
}
